package org.example.springboot01.Interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.example.springboot01.utils.JwtUtils;
import org.example.springboot01.utils.ThreadLocalUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

public class Myinterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(  HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            //实现thead 多线程用户登录 且不冲突
            String token = request.getHeader("Authorization");
            Map<String,Object> claims = JwtUtils.parseToken(token);
//            把claims 放入线程中
            ThreadLocalUtil.set(claims);
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
